<?php

namespace App\Repository\Order;

use App\Jobs\OrderSubmit;
use App\Models\Order\OrderModel as model;
use App\Repository\BaseRepository;
use App\Repository\Product\GoodsRepository;

class OrderRepository extends BaseRepository
{
    public function __construct()
    {
        $this->model = new model();
        $this->modelInfo = new OrderInfoRepository();
        $this->logModel = new OrderLogRepository;
        $this->productModel = new OrderProductRepository;
        $this->goodsModel = new GoodsRepository();
        parent::__construct();
    }

    //列表
    public function index($where)
    {
        $cron = $where;
        $cron['order'] = ['orderby' => 'id', 'orderdir' => 'desc'];
        // $cron['where'] = $where;
        // var_dump($cron,111111111);
        // var_dump($cron, 444444444);
        // DB::connection()->enableQueryLog();
        $data = $this->search($this->model, $cron);
        // $logs = DB::getQueryLog();
        // dd($logs);
        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => &$val) {
                if (!empty($val['channel_error_josn'])) {
                    $val['channel_error_josn'] = json_decode($val['channel_error_josn'], true);
                }
            }
        }
        return $data;
    }

    //添加
    public function add($data)
    {
        //必填 字段
        $mustField = [
            'orderno',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'orderno' => '订单编号不能为空',
        ];
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        if (!empty($insertData['status'])) {
            $insertData['status_desc'] = $this->model->getOrderStatusDesc($insertData['status']);
        }
        if (!empty($insertData['source'])) {
            $insertData['source_type'] = $this->model->getOrderSource($insertData['source']);
        }
        // var_dump($insertData);
        //操作日志记录
        $logDdata = [
            'orderno' => $insertData['orderno'],
            'shop_str' => $insertData['shop_str'],
            'shop_id' => $insertData['shop_id'],
            'remark' => date('Y-m-d H:i:s') . '提交信息',
        ];
        $this->logModel->add($logDdata); // 存入操作日志
        $insertData['created_at'] = date('Y-m-d H:i:s');
        $res = $this->model->insertGetId($insertData);
        $insertData['order_id'] = $res;
        // $insertData['channel_id'] = $insertData['sup_id'];
        // $insertData['channel_name'] = $insertData['sup_name'];
        // $insertData['channel_num'] = (count(json_decode($insertData['channel_error_josn']), true) + 1);
        $this->modelInfo->add($insertData); // 为了统计
        $productData = [
            'username' => $insertData['pay_name'],
            'idcard' => $insertData['pay_identity'],
            'phone' => $insertData['pay_phone'],
            'address' => $insertData['post_address'],
            'product_id' => !empty($insertData['product_id']) ? $insertData['product_id'] : '0',  //产品的id
            'shop_id' => $insertData['shop_id'],
        ];
        $this->productModel->add($productData); // 为了验证
        if ($res) {
            // 插入到队列中
            $this->upThree($insertData['orderno']);
            return $this->returnMsg(200, '上传成功');
        }
        return $this->returnMsg(1, '上传失败');
    }

    //删除
    public function del($where)
    {
        $flag = true;
        $msg = '未知错误';
        $code = 1;
        if (empty($where)) {
            $flag = false;
            $msg = '删除条件不能为空';
            $code = 2;
        }
        if ($flag) {
            $res = $this->model->where($where)->get();
            if (!$res) {
                $flag = false;
                $msg = '未查询到数据';
                $code = 3;
            }
        }
        if ($flag) {
            $del = $this->model->where($where)->delete();
            if ($del) {
                $msg = '删除成功';
                $code = 200;
            }
        }
        return $this->returnMsg($code, $msg);
    }
    //修改 用户修改

    /**
     * Undocumented function
     *
     * @param [type] $where 修改的条件
     * @param [type] $data  修改的数据
     * @param boolean $isMust 是否返回数据
     * @param boolean $isEditTrue 是否修改上游提交的数据
     * @return void
     */
    public function edit($where, $data, $isMust = false, $isEditTrue = true)
    {
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        // var_dump($data);
        //过滤字段
        //过滤字段
        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        if (isset($data['status']) && ($data['status'] == 0)) {
            $field['status'] = 0;
        }
        // var_dump($field, 66666666);
        //先查询是否存在
        $isTrue = $this->model->where($where)->first();
        if (!$isTrue) {
            return $this->returnMsg(3, '您无权限修改订单信息');
        }
        $str = ''; // 将某某数据修改成了 某某数据
        $isSubmit = false;
        $isEditData = ''; // 未修改
        $isedit = false;
        if (!empty($field['pay_identity'])) {
            $str = '用户修改';
            $isEditData .= '1+'; // 用户信息修改
        }
        if (!empty($field['goods_id'])) {
            $str = '商品信息修改';
            $isSubmit = true; // 商品信息修改
            $isEditData .= '2+';
        }
        if (!empty($field['product_id'])) {
            $str = '产品修改'; // 产品修改
            $isSubmit = true;
            $isEditData .= '3+';
        }
        if (!empty($field['goods_id'])) {
            // $resGoods = $this->goodsModel->where(['id' => $field['goods_id']])->first();
            $resGoods = $this->goodsModel->getOne(['id' => $field['goods_id']]);
            if (empty($resGoods)) {
                return $this->returnMsg(106, '未查询到商品');
            }
            $field['goods_id'] = $resGoods->id;
            $field['goods_code'] = $resGoods->goods_code;
            $field['goods_name'] = $resGoods->name;
            $field['product_id'] = $resGoods->product_id;
            $field['product_name'] = $resGoods->product_name;
            $field['product_code'] = $resGoods->product_code;
            $field['sup_shop_name'] = $resGoods->sup_shop_name;
            $field['shop_name_str'] = $resGoods->shop_name_str;
            $field['sup_goods_name'] = $resGoods->sup_goods_name;
            $field['shop_id_str'] = $resGoods->shop_id_str;
            $field['sup_goods_id_str'] = $resGoods->sup_goods_id_str;
            $field['sup_shop_id'] = $resGoods->sup_shop_id;
            $field['shop_name'] = $resGoods->shop_name;
            $field['shop_str'] = $resGoods->shop_str;
            $field['sup_goods_id'] = $resGoods->sup_goods_id;
            // 关联到产品信息
            if (!empty($resGoods->sup_goods_id_str)) {
                $resGoodsArr = explode('.', $resGoods->sup_goods_id_str);
                if (!empty($resGoodsArr[1])) {
                    $resGoodsProduct = $this->goodsModel->getOne(['id' => $resGoodsArr[1]]);
                    $field['product_id'] = $resGoodsProduct->product_id;
                    $field['product_name'] = $resGoodsProduct->product_name;
                    $field['product_code'] = $resGoodsProduct->product_code;
                }
            }
            // 需要将上游信息清空  是否清空
            // 如果修改的是商品的话 不需要清空上游信息的
            if ($isEditTrue) {
                $field['sup_id'] = 0;
                $field['sup_name'] = '';
                $field['sup_orderno'] = '';
            }

            // var_dump($field);
        }
        if (isset($field['status'])) {
            $isedit = true;
        }
        if (isset($field['status'])) {
            $field['status_desc'] = $this->model->getOrderStatusDesc($field['status']);
        }
        // var_dump(json_decode(json_encode($isTrue), true), 222222222);
        // var_dump($field, 111111111);
        foreach ($field as $key => $v) {
            // 用户信息 + 商品信息 + 产品信息
            if ($key == 'goods_name' || $key == 'product_name' || $key == 'status_desc' || $key == 'pay_name' || $key == 'pay_phone' || $key == 'pay_identity' || $key == 'post_province' || $key == 'post_city' || $key == 'post_area' || $key == 'post_address' || $key == 'shop_name' || $key == 'remark') {
                if ($isTrue->$key != $v) {
                    $isedit = true;
                    if ($key == 'shop_name') {
                        $str .= '分销商修改成' . $v;
                    } else {
                        $str .= '将' . $isTrue->$key . '修改为' . $v;
                    }
                }
            }
        }
        if (!$isedit) {
            $ordernum = $isTrue->orderno;

            dispatch(new OrderSubmit($ordernum, 'smsAndPushOrder'))->onQueue('TaskOrderSubmitDispose');

            return $this->returnMsg(200, '无修改任何数据');
        }
        // 添加操作日志
        $logDdata = [
            'orderno' => !empty($field['orderno']) ? $field['orderno'] : $isTrue->orderno,
            'remark' => date('Y-m-d H:i:s') . $str,
        ];
        if (!empty($isEditData)) {
            $field['is_edit'] = strpos($isTrue->is_edit, $isEditData) ? $isTrue->is_edit : ($isTrue->is_edit . $isEditData);
        }
        if (!empty($field['orderno'])) {
        }

        $this->logModel->add($logDdata); // 存入操作日志
        if (isset($field['orderno'])) {
            unset($field['orderno']);
        }
        // var_dump($field, 1111111);
        $res = $this->model->where($where)->update($field); //修改订单表
        if ($isSubmit) {
            //重新提交产品
        }
        if ($isMust && $res) {
            return $this->returnMsg(200, '修改成功');
        }
        if (!$isMust) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(3, '请重新修改');
    }

    // 系统修改
    public function editThree($where, $data, $isChannel = true)
    {
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        //先查询是否存在
        $isTrue = $this->model->where($where)->first();

        if (!$isTrue) {
            return $this->returnMsg(3, '您无权限修改订单信息');
        }
        // 防止重复修改订单状态   1 50
        if (!empty($field['status']) && !empty($isTrue->status) && $field['status'] <= $isTrue->status && $isTrue->status <= 40) {
            return $this->returnMsg(200, '该状态已提交过了');
        }
        // 将
        if (!empty($field['status']) && $field['status'] >= 50 && !$isChannel) {
            $resError = [
                'channel_id' => $isTrue->sup_id,
                'channel_name' => $isTrue->sup_name,
                'msg' => !empty($field['three_msg']) ? $field['three_msg'] : ''
            ];
            if (!empty($isTrue->channel_error_josn)) {
                $resError = json_decode($isTrue->channel_error_josn, true);
                $array_error = [];
                if (!in_array($isTrue->sup_id, $array_error)) {
                    $resError[] = [
                        'channel_id' => $isTrue->sup_id,
                        'channel_name' => $isTrue->sup_name,
                        'msg' => !empty($field['three_msg']) ? $field['three_msg'] : ''
                    ];
                }
            }

            $field['channel_error_josn'] = json_encode($resError);
            // 提交到第三方 重新提交到三方
            dispatch(new OrderSubmit($isTrue->orderno, 'createOrder'))->onQueue('TaskOrderSubmitDispose');
        }

        $str = '修改';
        if (!empty($field['status'])) {
            $field['status_desc'] = $this->model->getOrderStatusDesc($field['status']);
            $str .= $field['status_desc'];
        }


        $logDdata = [
            'orderno' => $isTrue->orderno,
            'remark' => date('Y-m-d H:i:s') . $str,
        ];
        $this->logModel->add($logDdata); // 存入操作日志
        // 修改
        $res = $this->model->where($where)->update($field); //修改订单表
        // $field['order_id'] = $isTrue->id;
        if (!empty($field['sup_id'])) {
            $field['channel_id'] = $field['sup_id'];
            $field['channel_name'] = $field['sup_name'];
            $field['channel_num'] = (count(json_decode($field['channel_error_josn']), true) + 1);
        }
        if (!empty($data['activat_at'])) {
            $field['activat_at'] = $data['activat_at'];
        }
        $this->modelInfo->edit(['order_id' => $isTrue->id], $field); // 为了统计
        if ($res) {
            return $this->returnMsg(200, '修改成功', ['orderno' => $isTrue->order]);
        }
        return $this->returnMsg(101, '修改失败');
    }

    //列表查询
    public function lists($where = [], $page = 1, $limit = 10)
    {
        $res = $this->search($this->model, $where, $page, $limit);

        return $res;
    }

    public function getOne($where, $field = ['*'])
    {
        $res = $this->model->where($where)->select($field)->orderBy('id', 'desc')->first();
        if (($res)) {
            return json_decode(json_encode($res), true);
        }
        return $res;
    }

    //下单
    public function orderSubmit()
    {
    }
    // 处理订单的状态
    // 订单的状态 1: 返回的物流等信息 修改 2:
    public function editOrderStatus($data)
    {
        if (empty($data)) {
            return $this->returnMsg(1, '修改的数据为空');
        }
        if (empty($data['orderno'])) {
            return $this->returnMsg(2, '订单号不能为空');
        }
        $update = [];
        if (!empty($data['express_company']) && !empty($data['status']) && $data['status'] < 20) {
            $data['status'] = 20; // 已发货的订单
        }
        if (!empty($data['status'])) {
            $update['status'] = $data['status'];
            $update['status_desc'] = $this->model->getOrderStatusDesc($data['status']);
        }

        $where = [];
        if (!empty($data['orderno'])) {
            $where = ['orderno' => $data['orderno']];
            unset($data['orderno']);
        }
        // 查询订单 是否存在
        $isExist = $this->model->where($where)->select(['id'])->orderBy('id', 'desc')->first();
        if (!$isExist) {
            return $this->returnMsg(3, '未查询到订单');
        }
        $isTrue = $this->model->where(['id' => $isExist->id])->update($update);
        if ($isTrue) {
            $this->modelInfo->edit($update);
        }
        return $isTrue;
    }

    // 获取订单状态 和来源
    public function getOrderStatus()
    {
        $data = $this->model->orderStatus();
        $datas = [];
        foreach ($data as $key => $v) {
            $datas[] = [
                'id' => $key,
                'value' => $v
            ];
        }
        return $this->returnMsg(200, '查询成功', $datas);
    }

    public function getOneOrderStatus($status = '')
    {
        $data = $this->model->orderStatus();
        if (isset($status)) {
            return $data[$status];
        }
        return $data;
    }

    public function getOrderSource()
    {
        $data = $this->model->getSourceType();
        $datas = [];
        foreach ($data as $key => $v) {
            $datas[] = [
                'id' => $key,
                'value' => $v
            ];
        }
        return $this->returnMsg(200, '查询成功', $datas);
    }

    public function getOneOrderSource($type)
    {
        $data = $this->model->getSourceType();
        if (isset($type)) {
            return $data[$type];
        }
        return $data;
    }

    //异步的时候 提交到第三方
    public function upThree($ordernum = '', $type = '')
    {
        if (empty($type)) {
            dispatch(new OrderSubmit($ordernum, 'createOrder'))->onQueue('TaskOrderSubmitDispose');
        }
        if (!empty($type)) {
            $time = 60 * 60 * 4;
            // Queue::later(Carbon::now()->addMinutes(10), new OrderSubmit($ordernum, 'createOrder'));
            dispatch(new OrderSubmit($ordernum, 'createOrder', $time))->onQueue('TaskOrderSubmitDispose');
        }
        return 1;
    }

    // 修改分销商
    public function editDistAll($array = [])
    {
        if (empty($array['dist_id'])) {
            return $this->returnMsg(101, '分销商不能为空');
        }
        // 1: 检验是否是分销商
        // 2:
        if (empty($array['goodsAllid'])) {
            return $this->returnMsg(102, '修改订单信息不能为空');
        }
        foreach ($array['goodsAllid'] as $key => $v) {
            $where = [
                'id' => $v
            ];
            // 查询的是订单
            $ordersArr = $this->getOne($where);
            $goods_id = $ordersArr['goods_id'];
            $res = $this->editDistOne($v, $array['dist_id'], $goods_id);
            if (!empty($res['code']) && $res['code'] != 200) {
                break;
            }
        }
        if (!empty($res)) {
            return $res;
        }
        return $this->returnMsg(200, '修改成功', []);
    }

    /**
     * Undocumented function
     *
     * @param [type] $dist_id 分销商id
     * @param [type] $goods_id  供应商的商品id
     * @return void
     */
    public function editDistOne($orderid, $dist_id, $goods_id, $editData = [])
    {
        // 查询分销商的商品
        $where = [
            'shop_id' => $dist_id,
            'sup_goods_id' => $goods_id
        ];
        // 查询出来商品信息
        // var_dump($where);

        $goodsData = $this->goodsModel->getOne($where);
        // var_dump($goodsData);
        if (!($goodsData)) {
            return $this->returnMsg(100, '未查询到商品信息');
        }
        // 然后修改商品信息
        $update = [
            'shop_id' => $dist_id,
            'goods_id' => $goodsData->id
        ];
        if (!empty($editData)) {
            $update = array_merge($update, $editData);
        }
        // 注意下商品
        // var_dump($update, 111111111);
        $editWhere = [
            'id' => $orderid
        ];
        $res = $this->edit($editWhere, $update, false, false);
        return $res;
    }
}
